/**
 * 
 */
package com.colombounplug.geoshopper;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * CRUD operations for the GeoShopper application.
 * @author anuradha.uduwage
 *
 */
public class ShoppingListDbAdapter {

	public static final String KEY_ITEM = "item";
	public static final String KEY_ROWID = "_id";
	
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;
	
	private final Context mContext;
	
	private static String DATABASE_CREATE = "create table itemlist(_id integer primary key autoincrement, " 
		+ "item text not null);";
	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "itemlist";
	private static final int DATABASE_VERSION = 2;

	private static final String TAG = "ShoppingListDbAdapter";
	
	private static class DatabaseHelper extends SQLiteOpenHelper {
		/**
		 * @param context
		 */
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

		/**	
		 * Create the database if it doest exsist.
		 */
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
	        db.execSQL("DROP TABLE IF EXISTS notes");
	        onCreate(db);
		}		
	}
	/**
	 * Takes the context to allow the database to be opened/created.
	 * @param context
	 */
	public ShoppingListDbAdapter(Context context) {
		this.mContext = context;
	}
	
	/**
	 * Open the database, if it can't open try to create a new instance.
	 * @return
	 * @throws SQLException
	 */
	public ShoppingListDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		mDbHelper.close();
	}
	
	/**
	 * create a new item, if the item is successfully created return row id.
	 * @param item
	 * @return
	 */
	public long createItem(String itemValue) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_ITEM, itemValue);
		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}
	
	/**
	 * Delete item based on given id.
	 * @param rowId
	 * @return
	 */
	public boolean deleteItem(long rowId) {
		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
    /**
     * Return a Cursor over the list of all items in the database
     * 
     * @return Cursor over all items
     */
    public Cursor fetchAllItems() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ITEM}, 
        		null, null, null, null, null);
    }
    
    /**
     * Return a Cursor positioned at the item that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchItem(long rowId) throws SQLException {

        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, 
        		KEY_ITEM}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of item to update
     * @param itme value 
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateItem(long rowId, String title, String item) {
        ContentValues args = new ContentValues();
        args.put(KEY_ITEM, item);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Return all database records as an array
     * @return
     */
	public ArrayList<String> getAllItems() {
		ArrayList<String> items = new ArrayList<String>();
    	//get all the items from the database and generate list
    	Cursor cursor = this.fetchAllItems();
    	cursor.moveToFirst();
    	while (cursor.isAfterLast() == false) {
    		items.add(cursor.getString(1));
    	}
    	return items;
	}    
}
